<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once ( LIB_DIR.'search/usersearch.php' );
require_once ( LIB_DIR.'classes/Pager.php' );
require_once ( LIB_DIR.'model/UserDAO.php' );

$pageVars = array();
$supportedSortBy = array( "review_count", "add_shop_count", "add_product_count", "contribution" );

if( !isset( $_GET['q'] ) ) {
//do nothing, just display
}
else{
	$keyword = $_GET['q'];
	$pageVars['keyword'] = $keyword;

	$searchType = NORMAL_QUERY;
	$userSearch = new UserSearch();

	$sortby = "review_count";
	if( isset( $_GET['sortby']) && in_array( $_GET['sortby'], $supportedSortBy) ){
		$sortby = edp_db_input( $_GET['sortby'] );
		$searchType = SORT_QUERY;
	}

        $sortby = 'contribution-desc';
	if( isset( $_GET['sortby'] ) )
		$sortby = $_GET['sortby'];
	//determine search type
	$isDesc = false;
	if( !empty( $sortby ) ) {
		$pageVars['sortby'] = $sortby;

		//parse sort
		//price0 is sort by price asc and price1 is sortby price desc
		$sortbyArray = explode( "-", $sortby );
		if( count($sortbyArray) == 2 ){
			$sortby = $sortbyArray[0];
			$isDesc = $sortbyArray[1] == "asc"? false : true;
		}
		else {
			$sortby = "";
		}

		if( $sortby != "" ){
			if( $searchType == FILTER_QUERY ) {
				$searchType = FILTER_SORT_QUERY;
			}
			else {
				$searchType = SORT_QUERY;
			}
		}
	}

	$page = 1;
        if( isset( $_GET['p'] ) ){
            $page = intval( $_GET['p'] );
	}

	$result = array();
	switch ($searchType) {
		case NORMAL_QUERY:
			$result = $userSearch->Query( $keyword, $page );
			break;
		case SORT_QUERY:
			$result = $userSearch->SortQuery($keyword, $sortby, $page, $isDesc);
			break;
		default:
			$result = $userSearch->Query( $keyword, $page );
	}

	$pageVars['result'] = $result;
	if( $result['total'] > 0 ) {
		$userDAO = new UserDAO();
		$dbRes = $userDAO->GetUserInfoByIdList( $result['matchIds'] );

		$highLighRes = array();
		if( $dbRes ){
			foreach( $dbRes as $row ) {
				$row['nick_plain'] = $row['nick'];
				//assemble field to highlight : shopname, shop description, nick, location, paymethod, tag, feature
				$arrToHighlight = array
					(
						//hard code here, need to be modified later
						'nick' => $row['nick'],
						'email' => $row['email'],
						'name' => $row['name']
					);
				// merge database and high light result array
				$row = array_merge( $row, $userSearch->BuildHighLight( $keyword, $arrToHighlight ) );

				//and set location and shopname

				$highLighRes[] = $row;
			}
		}

		$pageVars['dbRes'] = $highLighRes;

		// prepare page bar of search result
		$currentURL = htmlspecialchars( $_SERVER["REQUEST_URI"] );
		$currentURL = preg_replace( '/&p=[0-9]+/', "", $currentURL );
		$pageObj = new Pager( $currentURL, $pageVars['result']['total'], SHOP_INFO_PER_PAGE, $page, UP_RESULT_PAGE );

		$pageVars['pagebar'] = $pageObj->getBar();
	}
}
?>
